package com.zhuxin.common;

import com.CommWxApplication;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.client.RestTemplate;
import sun.misc.Request;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebFilter(urlPatterns = "/*", filterName = "permissionsFilter")
public class PermissionsFilter implements Filter {
    @Value("${wx.appId}")
    private String appid;
    @Value("${wx.appSecret}")
    private String appSecret;
    @Autowired
    private RestTemplate restTemplate;

    public static final String userinfoUrl="https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN";
    public static final String userinfUrl="https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code";
    public static final String anthUrl="https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("PermissionsFilter初始化");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String code = servletRequest.getParameter("code");
        String result=null;
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        String uri=request.getRequestURI();
        if(uri.indexOf("wxinf")!=-1 || uri.indexOf("MP_verify_KXV1H4Vu6C4faxQH.txt")!=-1 ||
        uri.toLowerCase().endsWith(".css") || uri.toLowerCase().endsWith(".js") ||
        uri.toLowerCase().endsWith(".ico")
                ){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        if(UtilTools.isNullOrBlank(code)){
            String requestUrl = request.getRequestURL().toString();
            String queryurl=request.getQueryString();
            if(null!=queryurl){
                requestUrl+="?"+queryurl;
            }
            String url=anthUrl;
            url=UtilTools.replaceStr(url,"{0}",appid);
            url=UtilTools.replaceStr(url,"{1}",requestUrl);
            HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
            System.out.println("requestUrl:"+requestUrl);
            System.out.println(url);
            httpServletResponse.sendRedirect(url);
        }else{
            String url = userinfUrl;
            url = UtilTools.replaceStr(url, "{0}", appid);
            url = UtilTools.replaceStr(url, "{1}", appSecret);
            url = UtilTools.replaceStr(url, "{2}", code);
            String tkstr = restTemplate.getForObject(url, String.class);
            JSONObject json = new JSONObject(tkstr);
            String token = json.getString("access_token");
            String openid = json.getString("openid");
            url = userinfoUrl;
            url = UtilTools.replaceStr(url, "{0}", token);
            url = UtilTools.replaceStr(url, "{1}", openid);
            result = restTemplate.getForObject(url, String.class);

            //拿当前访问的域名
            Map<String,Object> localMap = new HashMap<>();
            localMap.put("token",token);
            localMap.put("openid",openid);
            localMap.put("result",result);
            localMap.put("host",request.getHeader("host"));
            CommWxApplication.threadMap.set(localMap);
            filterChain.doFilter(servletRequest,servletResponse);
        }

    }

    @Override
    public void destroy() {
        System.out.println("PermissionsFilter已经销毁");
    }
}
